package org.framework.lazy.cloud.network.heartbeat.protocol.actuator;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.protocol.utils.FullHttpRequestUtils;

import java.net.URI;

/**
 * http 协议代理执行器
 */
@Slf4j
public abstract class AbstractNettyHttpProxyActuator implements NettyHttpProxyActuator {


    /**
     * 是否允许代理
     *
     * @param host 访问主机地址
     * @param port 访问端口
     */
    public abstract boolean support(String host, int port);

    /**
     * 获取代理通道
     *
     * @param originChannel   原始通道
     * @param fullHttpRequest 消息体
     * @param host            访问主机地址
     * @param port            访问端口
     */
    public abstract Channel createProxyChannelThenSend(Channel originChannel, FullHttpRequest fullHttpRequest, String host, int port);


    /**
     * 消息发送
     *
     * @param proxyChannel    代理通道
     * @param fullHttpRequest 消息体
     */
    public void doSend(Channel proxyChannel, FullHttpRequest fullHttpRequest) {
        proxyChannel.writeAndFlush(FullHttpRequestUtils.toByteBuf(fullHttpRequest));
    }

    /**
     * 发送消息
     *
     * @param originChannel   原始通道
     * @param fullHttpRequest 消息体
     */
    @Override
    public void send(Channel originChannel, FullHttpRequest fullHttpRequest) throws Exception {

        URI uri = new URI(fullHttpRequest.uri());
        String host = uri.getHost();
        int port = uri.getPort();
        if (port == -1) {
            port = 80;
        }
        if (support(host, port)) {
            Channel proxyChannel = createProxyChannelThenSend(originChannel, fullHttpRequest, host, port);

        } else {
            log.warn("不支持这个请求的代理 host:{},port:{}", host, port);
        }
    }
}
